package com.lxk.concurrency.example.count;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

import com.lxk.concurrency.annoations.NotThreadSafe;

/**
 * @Description 同一时刻，count 可以被多个线程执行，导致线程不安全
 *
 * @author 堆堆堆
 * @date 2018年5月25日 上午11:32:54
 */
@NotThreadSafe
public class CountExample1 {

	// 请求总数
	public static int clientTotal = 5000;

	// 同时并发执行的线程数
	public static int threadTotal = 200;

	public static int count = 0;

	public static void main(String[] args) throws Exception {
		ExecutorService executorService = Executors.newCachedThreadPool();
		final Semaphore semaphore = new Semaphore(threadTotal);

		// 闭锁，指定大小
		final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);

		for (int i = 0; i < clientTotal; i++) {

			executorService.execute(() -> {
				try {

					semaphore.acquire();
					add();
					semaphore.release();

				} catch (Exception e) {
					System.out.println(e);
				}
				
				// 初始化容量 -1 
				countDownLatch.countDown();
			});
		}
		
		// 将线程挂起阻塞，值到 0 就全部释放
		countDownLatch.await();
		
		// 关闭线程池
		executorService.shutdown();

		System.out.println("count:" + count);
	}

	private static void add() {
		count++;
	}
}
